package cn.jhz.learn.community_dynamic.app.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.jhz.learn.community_dynamic.common.bean.JsonData;
import cn.jhz.learn.community_dynamic.common.exception.RequestException;
import cn.jhz.learn.community_dynamic.dao.UserJpaRepository;
import cn.jhz.learn.community_dynamic.manager.UserManager;
import cn.jhz.learn.community_dynamic.model.UserEntity;
import cn.jhz.learn.community_dynamic.security.helper.LoginHelper;
import cn.jhz.learn.community_dynamic.vo.wbms.UserView;

@RestController
@RequestMapping("api/")
public class RelationController {

    private final UserJpaRepository userJpaRepository;
    private final UserManager userManager;


    @Autowired
    public RelationController(UserJpaRepository userJpaRepository, UserManager userManager) {
	super();
	this.userJpaRepository = userJpaRepository;
	this.userManager = userManager;
    }

    @PostMapping(value = "auth/add_black", consumes = "application/x-www-form-urlencoded")
    @PreAuthorize("hasAuthority('relation::post_black')")
    public JsonData addBlack(@RequestParam("black_id") Long blackId) {
	Optional<UserEntity> blackEntity = this.userJpaRepository.findByLoginId(blackId);
	if (blackEntity.isPresent()) {
	    UserEntity user = (UserEntity) LoginHelper.getLoginUser().get();
	    user.addBlack(blackEntity.get());
	    this.userJpaRepository.saveAndFlush(user);
	} else {
	    throw new RequestException("无效用户,添加失败!");
	}

	return JsonData.newSuccessInstance();
    }

    @DeleteMapping(value = "auth/remove_black", consumes = "application/x-www-form-urlencoded")
    @PreAuthorize("hasAuthority('relation::delete_black')")
    public JsonData removeBlack(@RequestParam("black_id") Long blackId) {

	Optional<UserEntity> blackEntity = this.userJpaRepository.findByLoginId(blackId);
	if (blackEntity.isPresent()) {
	    this.userManager.deleteBlack((UserEntity) LoginHelper.getLoginUser().get(), blackEntity.get());
	} else {
	    throw new RequestException("无效用户,修改失败!");
	}

	return JsonData.newSuccessInstance();
    }
    
    @PostMapping(value = "auth/follow", consumes = "application/x-www-form-urlencoded")
    @PreAuthorize("hasAuthority('relation::post_follow')")
    public JsonData addfollow(@RequestParam("follow_id") Long followId) {

	Optional<UserEntity> followEntity = this.userJpaRepository.findByLoginId(followId);
	if (followEntity.isPresent()) {
	    UserEntity user = (UserEntity) LoginHelper.getLoginUser().get();
	    user.addFollow(followEntity.get());
	    this.userJpaRepository.saveAndFlush(user);
	} else {
	    throw new RequestException("无效用户,添加失败!");
	}

	return JsonData.newSuccessInstance();
    }

    @DeleteMapping(value = "auth/unfollow", consumes = "application/x-www-form-urlencoded")
    @PreAuthorize("hasAuthority('relation::delete_follow')")
    public JsonData removeFollow(@RequestParam("follow_id")Long followId) {
	// TODO 检验blackId合法性
	Optional<UserEntity> followerEntity = this.userJpaRepository.findByLoginId(followId);
	if (followerEntity.isPresent()) {
	    this.userManager.deleteFollow(((UserEntity) LoginHelper.getLoginUser().get()), followerEntity.get());
	} else {
	    throw new RequestException("无效用户,添加失败!");
	}

	return JsonData.newSuccessInstance();
    }
   
    @GetMapping("auth/friends/{page}")
    @PreAuthorize("hasAuthority('relation::get_mutual_concern')")
    public JsonData getPerFriends(@PathVariable("page") Integer page) {
	UserEntity requestEntity = (UserEntity) LoginHelper.getLoginUser().get();
	return JsonData.newSuccessInstance(this.userJpaRepository.findByFollowsAndFollowedsAndIdNot(requestEntity, requestEntity, requestEntity.getId(), PageRequest.of(page - 1 , 10)).map(UserView.adpt));
    }
    
    @GetMapping("auth/fens/{page}")
    @PreAuthorize("hasAuthority('relation::get_followed')")
    public JsonData getPerFens(@PathVariable("page") Integer page) {
	UserEntity requestEntity = (UserEntity) LoginHelper.getLoginUser().get();
	return JsonData.newSuccessInstance(this.userJpaRepository.findByFollows(requestEntity, PageRequest.of(page - 1 , 10)).map(UserView.adpt));
    }
    
    @GetMapping("auth/follows/{page}")
    @PreAuthorize("hasAuthority('relation::get_follow')")
    public JsonData getPerFollow(@PathVariable("page") Integer page) {
	UserEntity requestEntity = (UserEntity) LoginHelper.getLoginUser().get();
	return JsonData.newSuccessInstance(this.userJpaRepository.findByFolloweds(requestEntity, PageRequest.of(page - 1 , 10)).map(UserView.adpt));
    }
}
